<?php
/*
 * @Author: 李明
 * @Date: 2022-01-13 10:13:52
 * @LastEditTime: 2022-02-18 09:40:00
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/order/OrderInterest/OrderInterestController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\order\OrderInterest;

use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Resources\Order\InterestOrder;
use App\Models\FamiliesMoneyRecord;
use App\Models\InterestRecord;
use Illuminate\Http\Request;
use App\Http\Controllers\Utils;
use App\Http\Controllers\BranchUtils;

class OrderInterestController extends Controller
{
    /**
     * @description: 新版本，查询 利息记录 待付款，付款中，已付款接口
     * @param {Request} $request
     * @return {*}
     */
    public function OrderInterestList(Request $request)
    {
        try {/*接参*/
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $size = $all['size'] ?? 15;
            $nowTime = date("Y-m-d", strtotime("+3 day"));
            $where = [];
            $where[] = ['is_exit', '2']; // 只查询没有提前中止的记录
            $end_time = '';
            // 1待打款，2打款中，3已打款
            if (isset($all['status'])) {
                $where[] = ["interest_record.status", $all['status']];
                if ($all['status'] == '1') {
                    $end_time = $all['end_time'] ?? $nowTime;
                }
            }
            if (isset($all['start_time'])) {
                $startTime = $all['start_time'];
                $where[] = ["interest_record.date", ">=", $startTime];
            }
            if ($end_time != '') {
                $where[] = ["interest_record.date", "<=", $end_time];
            }
            if (isset($all['order_id'])) {
                $where[] = ["interest_record.order_id", ">=", $all['order_id']];
            }
            $orderStatusList = ['3', '4', '6']; //订单状态 -1草稿， 1是待付款  2是审核中   3是待生效  4是已生效 5是拒绝  6是已结束
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数或者传参出现错误', 'OICOIL1');
        }
        try {
            $interest_list_model = InterestRecord::where($where)
                ->with('order.user')
                ->with('order.worker')
                ->with('order.bank_card.bank')
                ->with('order.product')
                ->whereHas('order', function ($query) use ($orderStatusList) {
                    $query->whereIn('order_status', $orderStatusList);
                })
                ->when(isset($all['user_name']), function ($query) use ($all) {
                    return $query->whereHas('order.user', function ($query_user) use ($all) {
                        $query_user->where('name', 'like', '%' . $all['user_name'] . '%');
                    });
                })
                ->when(isset($all['user_id']), function ($query) use ($all) {
                    return $query->whereHas('order.user', function ($query_user) use ($all) {
                        $query_user->where('id', $all['user_id']);
                    });
                })
                ->when(isset($all['contract_no']), function ($query) use ($all) {
                    return $query->whereHas('order', function ($query_order) use ($all) {
                        $query_order->where('contract_no', 'like', '%' . $all['contract_no'] . '%');
                    });
                })
                ->when(isset($all['tl_status']), function ($query) use ($all) {
                    $tl_status = $all['tl_status'];
                    return $query->whereHas('order', function ($queryOrder) use ($tl_status) {
                        $queryOrder->whereHas('bank_card', function ($queryBankCard) use ($tl_status) {
                            $queryBankCard->where('status', $tl_status);
                        });
                    });
                })
                ->when(isset($all['receivable_type']), function ($query) use ($all) {
                    return $query->where('receivable_type', $all['receivable_type']);
                })
                ->orderBy("interest_record.date", "desc")
                ->paginate($size);
            // 返回前端需要的数据
            $interest_list = InterestOrder::collection($interest_list_model);
            $return_datas = Utils::deal_page_resources($interest_list, $interest_list_model);
            return LMReturn::Success($return_datas);
        } catch (\Throwable $th) {
            return LMReturn::Error('查询出现错误', 'OICOIL2');
        }
    }

    /**
     * @description: 查询通联与普通打款记录某一段时间的打款总额
     */
    public function TotalOfInterestMoney(Request $request) {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        $branch_list = [];
        if (isset($all['branch_id'])) {
            $branch_array = BranchUtils::getAllBranchs();
            $branch_list = BranchUtils::getChildBranchs($all['branch_id'], $branch_array, [$all['branch_id']]);
        }
        $start_date = date('Y-m-d');
        $end_date = date('Y-m-d');
        if (isset($all['start_date']) && isset($all['end_date'])) {
            $start_date = $all['start_date'];
            $end_date = $all['end_date'];
            if ($start_date > $end_date) {
                $date = $start_date;
                $start_date = $end_date;
                $end_date = $date;
            }
        }
        $families_records = FamiliesMoneyRecord::select(
            'families_money_record.money',
            'families_money_record.pay_type',
            'families_money_record.type'
        )->whereIn('type', [1, 2])
        ->where('status', 5)
        ->where([['real_time', '<=', $end_date], ['real_time', '>=', $start_date]])
        ->when(count($branch_list)>0, function ($query) use ($branch_list) {
            return $query->whereIn('branch_id', $branch_list);
        })->get();
        $tl_in = 0;
        $tl_out = 0;
        $other_in = 0;
        $other_out = 0;
        foreach ($families_records as $families_record) {
            if ($families_record['type'] == 1) {
                if ($families_record['pay_type'] == 4) {
                    $tl_in = $tl_in + $families_record['money'];
                } else {
                    $other_in = $other_in + $families_record['money'];
                }
            } else {
                if ($families_record['pay_type'] == 4) {
                    if ($families_record['money'] > 0) {
                        $tl_out = $tl_out + $families_record['money'];
                    } else {
                        $tl_out = $tl_out - $families_record['money'];
                    }
                } else {
                    if ($families_record['money'] > 0) {
                        $other_out = $other_out + $families_record['money'];
                    } else {
                        $other_out = $other_out - $families_record['money'];
                    }
                }
            }
        }
        $reconciliation_data = [
            'tl_in'=>$tl_in,
            'tl_out'=>$tl_out,
            'other_in'=>$other_in,
            'other_out'=>$other_out
        ];
        return LMReturn::Success($reconciliation_data);
    }

}
